package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.HashMap;

public class CalculatorActivity extends AppCompatActivity implements View.OnClickListener {


    private TextView tv_result;
    private HashMap<Integer, String> numberMap;
    private HashMap<Integer, String> operatorMap;
    private CharSequence tv_result_text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculator);
        initViews();
        initMaps();

    }

    private void initMaps() {
        //用map来实现btn_seven和str.SEVEN的映射
        numberMap = new HashMap<>();
        numberMap.put(R.id.btn_zero, str.ZERO);
        numberMap.put(R.id.btn_one, str.ONE);
        numberMap.put(R.id.btn_two, str.TWO);
        numberMap.put(R.id.btn_three, str.THREE);
        numberMap.put(R.id.btn_four, str.FOUR);
        numberMap.put(R.id.btn_five, str.FIVE);
        numberMap.put(R.id.btn_six, str.SIX);
        numberMap.put(R.id.btn_seven, str.SEVEN);
        numberMap.put(R.id.btn_eight, str.EIGHT);
        numberMap.put(R.id.btn_nine, str.NINE);
        numberMap.put(R.id.btn_dot,str.DOT);



        //运算符map集合
        operatorMap = new HashMap<>();
        operatorMap.put(R.id.btn_divide, str.DIVIDE);
        operatorMap.put(R.id.btn_multiply, str.MULTIPLY);
        operatorMap.put(R.id.btn_plus, str.PLUS);
        operatorMap.put(R.id.btn_minus, str.MINUS);
        operatorMap.put(R.id.btn_sqrt, str.SQRT);
        operatorMap.put(R.id.btn_reciprocal, str.RECIPROCAL);
    }

    public void initViews(){
        //tv_result是计算界面
        tv_result = findViewById(R.id.tv_result);
        tv_result_text = tv_result.getText();

        int[] buttonIds = new int[]{R.id.btn_cancel,R.id.btn_divide,R.id.btn_multiply, R.id.btn_clear,
                R.id.btn_seven,R.id.btn_eight,R.id.btn_nine,R.id.btn_plus,R.id.btn_four,
                R.id.btn_five,R.id.btn_six,R.id.btn_minus,R.id.btn_one,R.id.btn_two,R.id.btn_three,
                R.id.btn_sqrt,R.id.btn_reciprocal,R.id.btn_zero,R.id.btn_dot,R.id.btn_equal};

        for (int id : buttonIds) {
            findViewById(id).setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        //获取当前的tv_result的内容

        //当前点击的按钮的id
        int id = v.getId();
        //点击数字
        if (numberMap.containsKey(id)) {
            clickNumber(id);
        }

        //点击运算符
        if (operatorMap.containsKey(id)) {
            clickOperator(id);
        }

        //点击等号
        if (v.getId() == R.id.btn_equal) {
            clickEqual();
        }
        //点击清除
        if (v.getId() == R.id.btn_clear) {
            clickClear();
        }
        //点击取消按钮
        if (v.getId() == R.id.btn_cancel) {
            clickCancel();
        }

    }

    //点击清除按钮
    public void clickCancel() {
        String tv_result_text_str = tv_result_text.toString();
        if (tv_result_text_str.length() == 1) {
            set_tv_result(str.ZERO);
            return;
        }
        set_tv_result(tv_result_text_str.substring(0, tv_result_text_str.length() - 1));
    }

    //对当前tv_result内容进行操作
    public void show_tv_result(int id, HashMap<Integer, String> mp) {
        StringBuilder sb = new StringBuilder();
        String number = mp.get(id);
        if (tv_result_text.equals(str.ZERO)) {
            tv_result.setText(number);
        } else {
            tv_result.setText(sb.append(tv_result_text).append(number));
        }

        tv_result_text = tv_result.getText();
    }

    //点击数字
    public void clickNumber(int id) {
        if (tv_result_text.equals(str.ERROR)) {
            clickClear();
        }
        show_tv_result(id, numberMap);

    }

    //点击运算符 + - * / √ ^-1
    public void clickOperator(int id) {
        //当前内容只有运算符
        if (OnlyContainsOperator() || isExistOperator()) {
            return;
        }
        if (tv_result_text.equals(str.ERROR)) {
            clickClear();
        }
        //展示tv_result
        show_tv_result(id, operatorMap);
    }

    //当前内容是否只包含操作符
    public boolean OnlyContainsOperator() {
        return tv_result_text == str.DIVIDE || tv_result_text == str.PLUS ||
                tv_result_text == str.MINUS || tv_result_text == str.MULTIPLY || tv_result_text
                == str.RECIPROCAL || tv_result_text == str.SQRT;
    }

    //当前内容是否是操作符（除了根号）开头
    public boolean headWithOperator() {
        String tv_result_text_str = tv_result_text.toString();
        return tv_result_text_str.startsWith(str.PLUS) || tv_result_text_str.startsWith(str.MINUS)
                || tv_result_text_str.startsWith(str.MULTIPLY) ||
                tv_result_text_str.startsWith(str.DIVIDE) ||
                tv_result_text_str.startsWith(str.RECIPROCAL);
    }

    //是否存在操作符
    public boolean isExistOperator() {
        String tv_result_text_str = tv_result_text.toString();
        return tv_result_text_str.contains(str.PLUS) || tv_result_text_str.contains(str.MINUS)
                || tv_result_text_str.contains(str.MULTIPLY) ||
                tv_result_text_str.contains(str.DIVIDE);
    }

    //操作符结尾
    public boolean isEndWithOperator(){
        String tv_result_text_str = tv_result_text.toString();
        return tv_result_text_str.endsWith(str.PLUS) || tv_result_text_str.endsWith(str.MINUS)
                || tv_result_text_str.endsWith(str.MULTIPLY) ||
                tv_result_text_str.endsWith(str.DIVIDE) || tv_result_text_str.endsWith(str.DOT);
    }
    //点击等号,这个逻辑是最复杂的，判断是否有操作符
    public void clickEqual() {
        //只包含一个操作符,以操作符开头后点击等号，都显示错误
        if (OnlyContainsOperator() || headWithOperator()||isEndWithOperator()) {
            set_tv_result(str.ERROR);
            return;
        }
        //计算
        calculate();
    }


    //点击清除
    public void clickClear() {
        set_tv_result(str.ZERO);
    }

    //更新界面
    public void set_tv_result(String str) {
        tv_result.setText(str);
        tv_result_text = tv_result.getText();//为了让显示的内容为计算的结果
    }

    //计算
    public void calculate() {
        String tvResultTextString = tv_result_text.toString();
        if (tvResultTextString.contains(str.PLUS)) {
            String[] split = tvResultTextString.split("\\" + str.PLUS);
            double leftNum = Double.parseDouble(split[0]);
            double rightNum = Double.parseDouble(split[1]);
            double sum = leftNum + rightNum;
            String res = sum + "";
            set_tv_result(res);
        }

        if (tvResultTextString.contains(str.MINUS)) {
            String[] split = tvResultTextString.split(str.MINUS);
            double leftNum = Double.parseDouble(split[0]);
            double rightNum = Double.parseDouble(split[1]);
            double minus = leftNum - rightNum;
            String res = minus + "";
            set_tv_result(res);
        }

        if (tvResultTextString.contains(str.MULTIPLY)) {
            String[] split = tvResultTextString.split(str.MULTIPLY);
            double leftNum = Double.parseDouble(split[0]);
            double rightNum = Double.parseDouble(split[1]);

            double multiply = leftNum * rightNum;
            String res = multiply + "";
            set_tv_result(res);
        }

        if (tvResultTextString.contains(str.DIVIDE)) {
            String[] split = tvResultTextString.split(str.DIVIDE);
            double leftNum = Double.parseDouble(split[0]);
            double rightNum = Double.parseDouble(split[1]);

            if (rightNum == 0) {
                set_tv_result(str.ERROR);
                return;
            }
            double multiply = leftNum / rightNum;
            String divide = multiply + "";

            set_tv_result(divide);
        }

        //根号只能在字符串头
        if (tvResultTextString.contains(str.SQRT)) {
            //根号不在字符串头部报错
            if (!tvResultTextString.startsWith(str.SQRT)) {
                set_tv_result(str.ERROR);
                return;
            }
            //在字符串头部
            double num = Double.parseDouble(tvResultTextString.substring(1));
            String res = Math.sqrt(num) + "";
            set_tv_result(res);
        }

        //求倒数
        if (tvResultTextString.contains(str.RECIPROCAL)) {
            //求倒数不在字符串尾部报错
            if (!tvResultTextString.endsWith(str.RECIPROCAL)) {
                set_tv_result(str.ERROR);
                return;
            }
            //在字符串尾部
            double num =(double)  1 / Double.parseDouble(tvResultTextString.substring(0,
                    tvResultTextString.length() - 3));
            String res = num + "";
            set_tv_result(res);
        }
    }
}